package edu.sysu.cshare.control;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.hibernate.Session;

import edu.sysu.cshare.dao.Homework;
import edu.sysu.cshare.dao.SubmitInfo;
import edu.sysu.cshare.dao.User;
import edu.sysu.cshare.util.ContinueFTP;
import edu.sysu.cshare.util.HibernateSessionFactory;

//TODO:更改一项作业属性信息
public class HomeworkManager {
	private User actor;

	public HomeworkManager(User actor) {
		this.actor = actor;
	}

	/**
	 * 添加一项新的作业信息到系统
	 * 
	 * @param homework
	 * @throws Exception
	 */
	public void addItem(Homework homework) throws Exception {

		if (actor.canManagerHomework()) {
			Session ss = HibernateSessionFactory.getSession();
			ss.beginTransaction();
			ss.save(homework);
			for (User stu : homework.getCourse().getStudents()) {
				SubmitInfo subinfo = new SubmitInfo(homework, null, stu);
				ss.save(subinfo);
			}
			if (homework.getDirPath() != null) {
				ContinueFTP ftp = new ContinueFTP();
				ftp.connect();
				ftp.makeDir(homework.getDirPath());
			}
			ss.getTransaction().commit();
		} else {
			throw new Exception("你不能添加作业信息,想提升权限吗? 请联系管理员");
		}
	}

	/**
	 * 管理员打包下载的作业项目
	 * 
	 * @param homework
	 *            打包下载的作业项目
	 * @throws Exception
	 */
	public void batchDownload(Homework homework) throws Exception {

		if (actor.canManagerHomework()) {
			// TODO
		} else {
			throw new Exception("你不能进行批量下载操作");
		}

	}

	/**
	 * 删除一项作业
	 * 
	 * @param homework
	 * @throws Exception
	 */
	public void deleteItem(Homework homework) throws Exception {
		if (actor.canManagerHomework()) {
			Session ss = HibernateSessionFactory.getSession();
			ss.delete(homework);
			ss.beginTransaction();
		} else {
			throw new Exception("你无权进行此操作 作业不是想不做就不做的");
		}

	}

	/**
	 * 用户重新下载自己提交过的作业
	 * 
	 * @param homework
	 * @throws Exception
	 */
	public void downloadMyHomework(Homework homework, String local)
			throws Exception {
		if (actor.canSubmit()) {
			ContinueFTP ftp = new ContinueFTP();
			try {
				ftp.connect();
				ftp.download(actor.getCorrespondingSubmitInfo(homework)
						.getSavePath(), local);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			throw new Exception("算了吧");
		}

	}

	/**
	 * 学生查看属于自己的所有作业
	 * 
	 * @return 提交信息列表
	 * @throws Exception
	 */
	public List<SubmitInfo> getAllHomeworks() throws Exception {

		if (actor.canSubmit()) {
			Session ss = HibernateSessionFactory.getSession();
			ss.beginTransaction();
			return ss.createQuery("from SubmitInfo si where si.user =:user ")
					.setEntity("user", actor).list();
		} else {
			throw new Exception("你就不用了吧");
		}

	}

	/**
	 * 老师查看自己布置的作业
	 * 
	 * @return 作业列表
	 * @throws Exception
	 */
	public List<Homework> getAssignments() throws Exception {
		if (actor.canManagerHomework()) {
			Session ss = HibernateSessionFactory.getSession();
			return ss
					.createQuery(
							"from Homework hm where hm.course.teacher =:teacher")
					.setEntity("teacher", actor).list();

		} else {
			throw new Exception("你又不是老师");
		}

	}

	public SubmitInfo getSubinfoById(long id) {
		Session ss = HibernateSessionFactory.getSession();
		ss.beginTransaction();
		return (SubmitInfo) ss.load(SubmitInfo.class, id);
	}

	public static Homework getHomeworkById(long id) {
		Session ss = HibernateSessionFactory.getSession();
		ss.beginTransaction();
		return (Homework) ss.load(Homework.class, id);
	}

	/**
	 * 通过判断提交日期是否为空 返回未提交作业的信息列表
	 * 
	 * @return
	 * @throws Exception
	 */
	public List<SubmitInfo> getUnsubmitHomeworks() throws Exception {
		if (actor.canSubmit()) {
			// NOTE WHY NO HQL HERE?
			List<SubmitInfo> result = new ArrayList<SubmitInfo>();
			for (SubmitInfo sinfo : actor.getSubmitInfos()) {
				if (sinfo.getSubmitDate() == null) {
					result.add(sinfo);
				}
			}
			return result;
		} else {
			throw new Exception("你真的需要交作业吗?");
		}

	}

	/**
	 * 提交作业 需要上传的作业项目:上传文件,设置提交日期 ,通过"上传"button调用
	 * 不需要上传的作业项目:filePath为null,只设置提交日期,通过"我做完了"button调用
	 * 
	 * @param homework
	 *            要提交的作业项目
	 * @param filePath
	 *            作业文件的绝对路径 如果是null则只设置做完日期
	 * @throws Exception
	 */

	public void submit(Homework homework, String filePath) throws Exception {
		if (actor.canSubmit()) {
			// TODO 过期处理逻辑
			// TODO 类型 大小限制
			Session ss = HibernateSessionFactory.getSession();
			ss.beginTransaction();

			SubmitInfo sinfo = actor.getCorrespondingSubmitInfo(homework);
			sinfo.setSubmitDate(Calendar.getInstance());

			if (filePath != null) {
				if (homework
						.getExtRestrict()
						.toLowerCase()
						.indexOf(
								filePath.toLowerCase().substring(
										filePath.lastIndexOf(".") + 1)) == -1) {
					throw new Exception("文件格式不符合要求");
				}
				File temp = new File(filePath);
				if( homework.getMaxSize()!=0){
					if(temp.length()/1024>homework.getMaxSize())
						throw new Exception("文件大小超过限制");
					
				}
				sinfo.setSavePath(homework.getDirPath()
						+ filePath.substring(filePath.lastIndexOf("\\")));
				ContinueFTP ftp = new ContinueFTP();
				ftp.connect();
				String filename = filePath
						.substring(filePath.lastIndexOf("\\"));
				ftp.upload(filePath, homework.getDirPath() + filename);
				System.out.println("[" + homework.getDirPath() + filename
						+ "] UPLOADED");
			}

			ss.save(sinfo);
			ss.getTransaction().commit();
		} else {
			throw new Exception("你真的需要交作业吗?");
		}

	}
}
